package guiAdministrator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;

import excepciones.DBException;

import administrator.Administrator;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class AdministratorMainGUI extends javax.swing.JFrame {
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JTextArea fieldConsulta;
	private JScrollPane jScrollPane4;
	private JTable tableResultado;
	private JScrollPane jScrollPane3;
	private JButton ejecutarConsulta;
	private JLabel jLabel1;
	private JTable tablaCampos;
	private JTable tablaTablas;
	
	//Variables
	private String[][] tablas;
	private String[][] camposTabla;
	private String[][] lastQueryResult;
	
	private Administrator dataMgr;
	
	private JFrame parent;

	/**
	* Auto-generated main method to display this JFrame
	*/
//	public static void main(String[] args) {
//		SwingUtilities.invokeLater(new Runnable() {
//			public void run() {
//				AdministratorMainGUI inst = new AdministratorMainGUI();
//				inst.setLocationRelativeTo(null);
//				inst.setVisible(true);
//			}
//		});
//	}
	
	public AdministratorMainGUI(JFrame parent) {
		super();
		
		this.dataMgr = new Administrator();
		this.parent = parent;
		
		try{
			//Conectar a la base de datos!
			this.dataMgr.connect("admin", "admin");
		}
		catch(DBException ex){
			JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
		}
		
		initGUI();
		
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	public AdministratorMainGUI(String user, String password) {
		super();
		this.dataMgr = new Administrator();
		
		try{
			//Conectar a la base de datos!
			this.dataMgr.connect(user, password);
		}
		catch(DBException ex){
			JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
		}
		
		initGUI();
	}
	
	public AdministratorMainGUI(Administrator dataMgr) {
		super();
		this.dataMgr = dataMgr;		
		initGUI();
	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
			this.setTitle("Administrador");
			this.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent evt) {
					thisWindowClosing(evt);
				}
				public void windowClosed(WindowEvent evt) {
					thisWindowClosed(evt);
				}
			});
			{
				jScrollPane1 = new JScrollPane();
				getContentPane().add(jScrollPane1);
				jScrollPane1.setBounds(12, 12, 221, 152);
				jScrollPane1.setSize(220, 152);
				{
					tablaTablas = new JTable();
					jScrollPane1.setViewportView(tablaTablas);
					tablaTablas.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							tablaTablasMouseClicked(evt);
						}
					});
				}
			}
			{
				jScrollPane2 = new JScrollPane();
				getContentPane().add(jScrollPane2);
				jScrollPane2.setBounds(252, 12, 220, 152);
				{
					tablaCampos = new JTable();
					jScrollPane2.setViewportView(tablaCampos);
				}
			}
			{
				jLabel1 = new JLabel();
				getContentPane().add(jLabel1);
				jLabel1.setText("Consulta:");
				jLabel1.setBounds(12, 170, 60, 23);
			}
			{
				ejecutarConsulta = new JButton();
				getContentPane().add(ejecutarConsulta);
				ejecutarConsulta.setText("Ejecutar Consulta");
				ejecutarConsulta.setBounds(85, 312, 308, 23);
				ejecutarConsulta.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						ejecutarConsultaActionPerformed(evt);
					}
				});
			}
			{
				jScrollPane3 = new JScrollPane();
				getContentPane().add(jScrollPane3);
				jScrollPane3.setBounds(12, 340, 460, 145);
				{
					tableResultado = new JTable();
					jScrollPane3.setViewportView(tableResultado);
				}
			}
			{
				jScrollPane4 = new JScrollPane();
				getContentPane().add(jScrollPane4);
				jScrollPane4.setBounds(13, 199, 460, 107);
				{
					fieldConsulta = new JTextArea();
					jScrollPane4.setViewportView(fieldConsulta);
					fieldConsulta.setBounds(19, 269, 456, 49);
				}
			}
			pack();
			this.setSize(500, 535);
			
			initTablas();
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	private void initTablas(){
		try{
			this.tablas = this.dataMgr.getTableNames();
			
			TableModel tablaTablasModel = 
					new DefaultTableModel(
						this.tablas,
						new String[] { "Nombre"});
			tablaTablas.setModel(tablaTablasModel);
		}
		catch(DBException ex){
			JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void fillTablaCampos(String nombreTabla){
		try{
			this.camposTabla = this.dataMgr.getTableFields(nombreTabla);
			
			TableModel tablaCamposModel = 
					new DefaultTableModel(
						this.camposTabla,
						new String[] { "Nombre"});
			tablaCampos.setModel(tablaCamposModel);
		}
		catch(DBException ex){
			JOptionPane.showMessageDialog(this, "Hubo un error al conectar con la base de datos.", "Administrador", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void fillTablaTablas()
	{
		try{
			this.tablas = this.dataMgr.getTableNames();

			TableModel tablaTablasModel = 
					new DefaultTableModel(
							this.tablas,
							new String[] { "Nombre"});
			tablaTablas.setModel(tablaTablasModel);
		}
		catch(DBException ex){
			JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void ejecutarConsultaActionPerformed(ActionEvent evt) {
		String sql = this.fieldConsulta.getText();
		String tipoOperacion = sql.substring(0, 6).toLowerCase(Locale.ENGLISH);
		if (!tipoOperacion.equals("select"))
		{
			boolean error = false;
			try{
				this.dataMgr.ejecutarUpdate(sql);
				this.fillTablaTablas();
			}
			catch(DBException ex){
				error = true;
				JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
			}
			catch(Exception ex){
				error = true;
				JOptionPane.showMessageDialog(this, "Hubo un error al ejecutar la consulta, revise los campos ingresados.", "Administrador", JOptionPane.ERROR_MESSAGE);
			}
			if(!error)
				JOptionPane.showMessageDialog(this, "Operacion ejecutada correctamente.", "Administrador", JOptionPane.INFORMATION_MESSAGE);
		}
		else
		{
			try{
				this.lastQueryResult = this.dataMgr.ejecutarConsulta(sql);

				TableModel tablaResultadoModel = 
						new DefaultTableModel(
								this.lastQueryResult,
								this.dataMgr.getLastQueryFields()); //Aca van los nombres de los campos consultados esto esta mal!
				tableResultado.setModel(tablaResultadoModel);
			}
			catch(DBException ex){
				JOptionPane.showMessageDialog(this, ex.getMessage(), "Administrador", JOptionPane.ERROR_MESSAGE);
			}
			catch(Exception ex){
				JOptionPane.showMessageDialog(this, "Hubo un error al ejecutar la consulta, revise los campos ingresados.", "Administrador", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private void tablaTablasMouseClicked(MouseEvent evt) {
		fillTablaCampos(this.tablas[this.tablaTablas.getSelectedRow()][0]);
	}
	
	private void thisWindowClosed(WindowEvent evt) {
		//this.parent.setVisible(true);
	}
	
	private void thisWindowClosing(WindowEvent evt) {
		if(this.parent != null){
			this.parent.setVisible(true);
		}
	}

}
